import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URI;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.imageio.ImageIO;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
//import org.apache.commons.httpclient.params.HttpMethodParams;
//import org.apache.commons.httpclient.*;
//import org.apache.commons.httpclient.methods.*;

public class browser {
	static int threadMax = 5;
	static int pageNO = 0;
	static int proxyPORT = 0;
	static boolean directLink = false;
	static String proxyURL = "";
	static HttpHost proxy = new HttpHost("com2-3f-c30-08-r200-5.savacus.net", 80, "http");
//	static HttpGet req = new HttpGet("/");
	static File imgdir = new File("_IMAGE");

	static boolean initApp() throws Exception {
		try {
			System.out.println("");
			System.out.println("");
			System.out.println("StartPage: Type start page like> 1 or u wnat (default:1)");
			String string = "";
			InputStreamReader input = new InputStreamReader(System.in);
			BufferedReader reader = new BufferedReader(input);
			string = reader.readLine();
			if (Integer.valueOf(string) > 1)
				pageNO = Integer.valueOf(string);
			else
				pageNO = 1;
			System.out.println("");
			System.out.println("");
			System.out.println("How many Download-Thread:");
			System.out.println("Type How many thread u want like> 2 or 5 or 100(considery ur PC performace)(default:5)");
			string = reader.readLine();
			if (Integer.valueOf(string) > 1)
				threadMax = Integer.valueOf(string);
			else
				threadMax = 5;
			System.out.println("");
			System.out.println("");
			System.out.println("PROXY:");
			System.out.println("Type JAPAN ProxyURL:port like> visit here: http://www.cybersyndrome.net/country.html#j");
			System.out.println("www22239u.sakura.ne.jp:8080");
			System.out.println("d016-060.intsurf.ne.jp:8909");
			System.out.println("113x35x64x26.ap113.ftth.ucom.ne.jp:80");
			System.out.println("or press \"NO\" to direct link without proxy");
			string = reader.readLine();
			if (string.equalsIgnoreCase("no")) {
				directLink = true;
			} else {
				proxyURL = String.valueOf(string).split(":")[0];
				proxyPORT = Integer.valueOf(string.split(":")[1]);
			}

			return true;
		} catch (Exception e) {
			return false;
		}

	}

	public static void main(String[] args) throws Exception {
		System.err.println("xlinx-4u Image downloader version1 #visit: http://decade.tw or http://arduino.tw ");
		System.err.println("WARRING:: Before using this tool. plz make sure u can visit http://4u-beautyimg.com/ by proxy in JAPAN");
		System.err.println("java -jar x4u.jar 1 5 proxy.com:80");
		System.err.println("java -jar x4u.jar 1 5 NO");
		boolean allSet = false;
		if (args.length == 3) {
			pageNO = Integer.valueOf(args[0]);
			threadMax = Integer.valueOf(args[1]);
			if (String.valueOf(args[2]).equalsIgnoreCase("no")) {
				directLink = true;
			} else {
				proxyURL = String.valueOf(args[2]).split(":")[0];
				proxyPORT = Integer.valueOf(args[2].split(":")[1]);
			}
			allSet = true;
		} else
			while (!allSet) {
				allSet = initApp();
			}

		if (!imgdir.isDirectory())
			imgdir.mkdir();
		// mainx.start();
		ExecutorService service = Executors.newFixedThreadPool(threadMax);
		for (int pageno = pageNO; pageno <= 99999; pageno++) {
			final int count = pageno;
			service.submit(new Runnable() {
				public void run() {
					try {
						runPage(count);
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			});
		}

		service.shutdown(); // 最後記得關閉Thread pool

	}

	public static void runPage(int pageno) {
		// httpclient.getParams().setParameter("http.protocol.single-cookie-header",
		// true);
		// httpclient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
		// new DefaultHttpMethodRetryHandler(3, false));
		// httpclient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
		// httpclient.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
		// HttpGet req = new HttpGet("/");
		// con.setDefaultHeaders(new NVPair[] { new NVPair("User-Agent",
		// "Mozilla/4.5") });
		// req.setURI(new
		// URI("http://4u-beautyimg.com/?page="+String.valueOf(pageno)));
		// String urlurl="4u-beautyimg.com/?page="+String.valueOf(pageno);
		// String urlurl="google.com";
//			HttpHost target = new HttpHost("4u-beautyimg.com", 80, "http");

		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet();
		try {
			if (!directLink) {
				httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
			}
			httpget.setURI(new URI("http://4u-beautyimg.com/?page="+String.valueOf(pageno)));
			HttpResponse rsp = httpclient.execute(httpget);
			HttpEntity entity = rsp.getEntity();
			String relaLadyURL = "";
			String lady = "";
			if (entity != null) {
				lady = "";
				String s = EntityUtils.toString(entity);
				BufferedReader reader = new BufferedReader(new StringReader(s));
				while ((lady = reader.readLine())!=null) {
					lady=lady.trim();
					// System.out.println(lady);
					try {
						
						if (lady.length()>10 && lady.startsWith("<p class=\"entry-img-src\">")) {
							relaLadyURL = lady.split("<p class=\"entry-img-src\">")[1].split("</p>")[0];
							lady = relaLadyURL.replaceAll("/", "_");
							System.out.print("\n##" + pageno + "##=> " + lady);

							File f = new File(imgdir.getAbsolutePath(), lady);
							if (!f.exists() && !lady.contains("?")) {
								BufferedImage bi = ImageIO.read(new URL("http://" + relaLadyURL));
								if (bi.getWidth() > 250) {
									ImageIO.write(bi, "jpg", f);
									System.out.print(" -- downloaded");
								} else
									System.err.print(" -- pic too small passed");
							} else
								System.err.print(" -- passed");
						}
					} catch (Exception e) {

						System.err.print(lady + " -- may remove by web.");
//						 e.printStackTrace();
					}
				}
				// System.out.println(EntityUtils.toString(entity));
			} else
				System.out.println("input page number like java xx 1");

		} catch (Exception e) {
			// System.err.print(""+e);
			e.printStackTrace();
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpclient.getConnectionManager().shutdown();
		}
	}// end of run
}